package com.tongguan.paypos.fragment;

import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tongguan.paypos.R;
import com.tongguan.paypos.base.BaseFragment;
import com.tongguan.paypos.common.AppConstants;
import com.tongguan.paypos.common.User;
import com.tongguan.paypos.utils.CipherUtils;
import com.tongguan.paypos.utils.SPUtils;
import com.tongguan.paypos.utils.ToastUtils;
import com.tongguan.paypos.view.CustomInputDialog;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Joylive on 2016/12/15 .
 */

public class SettingConnectFragment extends BaseFragment {

    @BindView(R.id.ll_communication)
    LinearLayout mLlCommunication;
    @BindView(R.id.btn_save_connect_type)
    Button mBtnSaveConnectType;
    @BindView(R.id.tv_connect)
    TextView mTvConnect;
    private int type;
    private String[] connects = {"默认", "生产连接", "测试连接", "域名连接"};

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_setting_communication, container, false);
        ButterKnife.bind(this, rootView);
        setTitle("通讯参数设置");
        type = (int) SPUtils.getSp(frmCtx, AppConstants.NET_CONNECT_TYPE, 0);
        mTvConnect.setText(connects[type]);
        initPwd();
        initEvent();
        return rootView;
    }

    private void initPwd() {
        new CustomInputDialog.Builder(frmCtx).setTitle("输入更改密码")
                .setPositiveButton(R.string.common_sure, pwd -> {
                    if (CipherUtils.KEY_9.equals(CipherUtils.md5(pwd))) {
                        ToastUtils.showCustom(frmCtx, "密码正确");
                    } else {
                        ToastUtils.showCustom(frmCtx, "密码错误");
                        onBack();
                    }
                }).setNegativeButton(R.string.common_cancel, (dialog, which) -> onBack()).show();
    }

    private void initEvent() {
        mLlCommunication.setOnClickListener(v ->
                new AlertDialog.Builder(frmCtx).setSingleChoiceItems(connects, type, (dialog, which) -> {
                    type = which;
                    mTvConnect.setText(connects[type]);
                    dialog.dismiss();
                }).show());

        mBtnSaveConnectType.setOnClickListener(v -> {
            SPUtils.setSP(frmCtx, AppConstants.NET_CONNECT_TYPE, type);
            ToastUtils.showCustom(frmCtx, "参数保存成功");
            User.getInstance().setLoginStatus(false);//重新登录
            User.getInstance().setNetConnectType(type);
        });
    }
}
